﻿PuppetPlay.Image = function (cfg) {
    var zoomFactor = cfg.zoomFactor? cfg.zoomFactor: PuppetPlay.Util.getZoomFactor();
    var config = {};

    config.image = cfg.obj;
    config.width = (cfg.width * zoomFactor + 0.5) | 0;
    config.height = (cfg.height * zoomFactor + 0.5) | 0;
    config.x = cfg.x ? ((cfg.x * zoomFactor + 0.5) | 0) : 0;
    config.y = cfg.y ? ((cfg.y * zoomFactor + 0.5) | 0) : 0;
       
    Kinetic.Image.apply(this, [config]);
    this.attrs.imageId = PuppetPlay.ImageCache.genImageId();
};

PuppetPlay.Image.prototype = {
    drawFunc: function(context) {    
        var width = this.getWidth();
        var height = this.getHeight();
        var imageCache = PuppetPlay.ImageCache;

        context.beginPath();
        context.rect(0, 0, width, height);
        context.closePath();
        this.fill(context);
        this.stroke(context);

        var image = this.attrs.image;
        var id = this.attrs.imageId;
        if(image) {
            if(!imageCache.hasCache(id)){
                imageCache.drawImage(id, image, width, height);
            }
            image = imageCache.getCanvas();
            cachePos = imageCache.getCache(id);
            // if cropping
            if(this.attrs.crop && this.attrs.crop.width && this.attrs.crop.height) {
                var cropX = this.attrs.crop.x ? this.attrs.crop.x : 0;
                var cropY = this.attrs.crop.y ? this.attrs.crop.y : 0;
                var cropWidth = this.attrs.crop.width;
                var cropHeight = this.attrs.crop.height;
                this.drawImage(context, this.attrs.image, cropX, cropY, cropWidth, cropHeight, 0, 0, width, height);
            }
            // no cropping
            else {
                this.drawImage(context, image, cachePos.x, cachePos.y, width, height, 0, 0, width, height);
            }
        }
    }
};

Kinetic.Global.extend(PuppetPlay.Image, Kinetic.Image);